import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { CpasIcon, LayoutB } from '../../../public/cpas-ui';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';

import { Popup } from 'devextreme-react/popup';
import TreeView from "devextreme-react/tree-view";

import { getApiData } from "../../services/cpasRequest"; // 附注导出，

import { useModel } from "umi";
import PubSub from 'pubsub-js'
import { unzip, importTemplate, getAccountAdujustIsSelect, getDesignTabelEditDateCompare, getdgTreeList, getDesignTabelEditDate } from "../exportResult/server";
import TreeList, { Column, Selection } from "devextreme-react/tree-list";
import { Modal, Progress, Tooltip, } from 'antd';
import { LoadPanel } from 'devextreme-react/load-panel';
import { history } from 'umi';
import TextBox from "devextreme-react/text-box";
import notify from "devextreme/ui/notify";
import AudTabPage from '~/src/components/PageTab/AudTabPage';
import SelectBox from "devextreme-react/select-box";
import DataGrid from "devextreme-react/data-grid";
import { formatterChinaTime } from "@/utils";
const ReportExport = (props: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, sjxmbh, zcbfid, sjnd } = initialState?.curPart;
    const [cataloguepath, setCataloguePath] = useState<string>('');
    const [firstTitle, setfirstTitle] = useState([
    ]
    );
    const [msg, setMsg] = useState("");
    const [loadPanelVisible, setLoadPanelVisible] = useState(false);
    const [secondTitle, setsecondTitle] = useState([]); // 第二栏目的显示标题
    const selectedDisclosureTable = useRef([]); // 选中的DisclosureTable
    const [currentid, setcurrentid] = useState(0);  // 当前选中的DisclosureTable的id
    const [zcbf, setzcbf] = useState({ accountDateSet: {}, accountDate: {}, zcbfinfo: { ReceivePerson: "",AuditReportDate: "" } });
    const audTabpage = AudTabPage.getInstance();

    // const [auditAjust, setauditAjust] = useState(false || []);


    const [isexport, setIsexport] = useState(false);
    const [isMaskOpen, setIsMaskOpen] = useState(true);
    const [auditAdjustFiterBiilType, setAuditAdjustFiterBiilType] = useState(-1);
    const [auditAdjustFiterAccountDate, setAuditAdjustFiterAccountDate] = useState(0);
    const [versionList, setVersionList] = useState(["全部"]);
    const [TapActiveKey, setTapActiveKey] = useState("1");
    const [dgdatalist, setDgdatalist] = useState([]); // 当前的渲染的数据列表
    const [ProgressInfoVisible, setProgressInfoVisible] = useState(false);
    const [ProgressInfoValue, setProgressInfoValue] = useState(0);
    const [isAllowNote, setIsAllowNote] = useState(false); // 附注能否导入
    const isAllowNoteRef= useRef(false); // 附注能否导入
    const treeViewRef = useRef<any>(null);
    const notes = useRef<any>(false || []);
    const auditAjust = useRef<any>(false || []);
    const report = useRef<string[] | boolean>(false);
    const ProgressCount = useRef({
        index: 0,
        count: 0,
    });
    // const [notes, setNotes] = useState<boolean | []>();
    // const [Trial, setTrial] = useState([{name:"未审财务报表",id:1,selected: true,isselected:true},{name:"审定财务报表",id:2,selected: true,isselected:true},{name:"试算平衡表",id:3,isselected:true,selected: true}]); 
    type firstTitleType = { id: number, items: [], isselected: boolean }[];
    const allnodedata = useRef<any>({
    });
    const TapActiveKeydgOrfj = useRef<any>({
        key: "1",
        dg: [],
        selectFj: [],
        selectdg: []
    });
    enum leftTitleList {
        zcfb = 1,
        dgfj = 2,
        auditAdjust = 3,
        notes = 4,
        report = 5,
    }

    useEffect(() => {
        PubSub.subscribe('call_progress_import', (msg, data: { count: number, msg: string, data: number }) => {
            ProgressCount.current.index = ProgressCount.current.index + 1
            if (ProgressCount.current.index === 1) {
                ProgressCount.current.count = ProgressCount.current.count  +data.count
            }
            setMsg(data.msg)
            setProgressInfoValueEvent(ProgressCount.current.index, ProgressCount.current.count)

        })

    }, []);
    useEffect(() => {
        //接受electron的proload.ts中下载事件 ipcRenderer.on('downloadStart'
        window.addEventListener('message', (data) => {
            ProgressCount.current.index = ProgressCount.current.index + 1
            console.log(data, ProgressCount.current)
            setProgressInfoValueEvent(ProgressCount.current.index, ProgressCount.current.count)
        });
        return () => {
            window.removeEventListener('message', () => {
                console.log('removeEventListener');
            });
        };
        //treeViewRef.current.
    }, []);

    // 渲染二级栏目,用一级栏目点击事件去渲染，首次进去手动执行次函数，手动执行此函数时，
    const leftonItemsChange = async (Event: any, config?: { id: number, items: [] }[]) => {
        // 获取当前的一级栏目id
        let id
        config = allnodedata.current.exportFirstIndex as []
        id = config[Event.itemIndex].id
        setcurrentid(id)
        setsecondTitle(config[Event.itemIndex].items)
    }
    const dgChangeTabsKey = async (e: any) => {
        // 数据在进去时获取，这一块是激活哪个tab显示
        if (e === '1') {
            TapActiveKeydgOrfj.current.key = "1"
            //  重新渲染，取接口返回的原始数据
            setDgdatalist(allnodedata.current.exportdgIndex)
        } else {
            TapActiveKeydgOrfj.current.key = "2"
            setDgdatalist(allnodedata.current.dgfj)
        }
    }
    // 附注部分切换
    const notechangeTabsKey = async (e: any) => {
        if (e === '1') {
            setTapActiveKey("1")
            let index = 0
            try {
                firstTitle.forEach((item: any) => {
                    if (item.id === 4) {
                        throw new Error("stop")
                    } else {
                        index = index + 1
                    }
                })
            } catch (error) {

            }

            leftonItemsChange({ itemIndex: index }, firstTitle)
        } else {
            setTapActiveKey("2")
            setsecondTitle(allnodedata.current.Trial)
        }
    }
    const getAccountAdujustInfo = async ({ DataId, BillType }: { DataId: any, BillType: any }) => {
        let config: { billType: number, DataId: number }[] = [];

        let auditAjustTem = allnodedata.current.adjust
        if (DataId != 0 && BillType != -1) {
            config = auditAjustTem.filter((p: { Data_ID: any; BillType: any; }) => p.Data_ID == DataId && p.BillType == BillType)
            auditAjust.current = config as [];
            return config
        }
        if (BillType != -1) {
            config = auditAjustTem.filter((p: { BillType: any; }) => p.BillType == BillType)
            auditAjust.current = config as [];
            return config
        }
        if (DataId != 0) {
            config = auditAjustTem.filter((p: { Data_ID: any; }) => p.Data_ID == DataId)
            auditAjust.current = config as [];
            return config
        }

        return auditAjustTem
    }
    const treeViewSelectionChanged = (e: { component: any; }) => {
        syncSelection(e.component);
    };
    const syncSelection = (treeView: { getSelectedNodes: () => any[]; }) => {
        const selectedEmployees = treeView
            .getSelectedNodes()
            .map((node: { itemData: any; }) => node.itemData);
        // console.log(selectedEmployees);
        // 定位不同的目录记住不同的选择 TwotreeViewSelectionChanged
        selectedDisclosureTable.current = selectedEmployees as [];
        // 控制导出按钮
        if (selectedEmployees.length === 0) {
            setIsexport(true)
        } else {
            setIsexport(false)
        }
    };
    const TwotreeViewSelectionChanged = (e: { component: any; }) => {
        TwosyncSelection(treeViewRef.current.instance.getSelectedNodes(), treeViewRef.current.instance.getNodes())
    };
    const TwosyncSelection = (
        getSelectedNodes: any[], getNodes: any[],
    ) => {
        const selectedEmployees =
            getSelectedNodes
                .map((node: { itemData: any; }) => node.itemData);
        // 定位不同的目录记住不同的选择 TwotreeViewSelectionChanged
        if (currentid === leftTitleList.zcfb) {
            setzcbf(allnodedata.current.Zcbfinfo)

        } if (currentid === leftTitleList.auditAdjust) {
            auditAjust.current = selectedEmployees as [];
            // setauditAjust(selectedEmployees as [])
        } if (currentid === leftTitleList.notes) {
            // 试算
            if (TapActiveKey === "1") {
                if (selectedEmployees.filter(a => a.selected === true && a.isselected === false).length) {
                    isAllowNoteRef.current=true;
  
                } else {
                    isAllowNoteRef.current=false;
                    setIsAllowNote(false)
                }
                notes.current = selectedEmployees.filter((a: { isselected: any; }) => a.isselected)

            }
            if (TapActiveKey === "2") {
                // 调接口时判断了，选中的节点，没有的不会渲染出来，默认全部导入
                allnodedata.current.selectTrial = selectedEmployees
                // setTrial()
            }
        } if (currentid === leftTitleList.report) {
            // 间接判断选中的节点
            if (selectedEmployees.length === 1) {
                if (selectedEmployees[0].id === 52) {

                    report.current = allnodedata.current.report.filter((a: any) => a !== "Generated")

                } else {
                    report.current = ["Generated"]
                }
            } else if (selectedEmployees.length === 2) {
                report.current = allnodedata.current.report
            } else {
                report.current = []
            }

        }
    };
    // 解压渲染
    const exportResult = async () => {
        // console.log(selectedDisclosureTable.current, typeof zcbf,audTabpage);
        let electronComponents: any;
        if (window.parent) {
            //@ts-ignore
            electronComponents = window.parent.electronComponents;
        } else {
            //@ts-ignore
            electronComponents = window.electronComponents;
        }
        //const dialog_result = await electronComponents.openDirectoryDialog();
        const dialog_result = await electronComponents.openDialog({
            properties: ['openFile'],
            filters: [{
                name: 'Aum Files',
                extensions: ["aum6"]
            }]
        });

        if (!dialog_result.filePaths.length) {
            return notify("请选择文件", "error", 1000)
        }
        const checkFolderPath = dialog_result.filePaths[0];
        setCataloguePath(checkFolderPath);
        // 调取解压到 临时目录
        //@ts-ignore
        let tempPath = window.main.mainObject.getAppPath() + "\\Temp\\";
        //@ts-ignore
        if (!window.main.mainObject.fileExists(tempPath)) {
            //@ts-ignore
            window.main.mainObject.createDirs(tempPath)
        }
        setLoadPanelVisible(true)
        const unzip_resultt = await unzip({ src: checkFolderPath, targetDir: tempPath });
        if (!unzip_resultt.ok) {
            setLoadPanelVisible(false)
            return notify("解压失败", "error", 1000)
        }
        // 读取页面显示栏目
        //@ts-ignore
        let config = await window.main.mainObject.loadJsonFromFile(`${tempPath}config.json`)
        if (config && zcbfid != config.zcbfid) {
            setLoadPanelVisible(false)
            notify(`文件包的组成部分id:${config.zcbfid} 和当前的项目不匹配，请谨慎操作`, "info", 3000)
        }
        // 保存全局变量
        allnodedata.current = config
        // 读取栏目
        for (let iterator of config.exportFirstIndex) {
            // if (iterator.id == leftTitleList.report) {
            // // 报告都是为不选中 ,又修改为选中
            // iterator.selected=false
            // iterator.items=iterator.items.map( (a:firstTitleType)=>{return {...a, selected:false}} )
            //存数据
            // setReport(config.report)
            // setreportData(config.report)
            // }
            if (iterator.id == leftTitleList.zcfb) {
                // 组成部分都是为不选中
                iterator.selected = false
                iterator.items = iterator.items.map((a: firstTitleType) => { return { ...a, selected: false } })
                //存数据
                setzcbf(config.Zcbfinfo)
            }



            if (iterator.id === leftTitleList.auditAdjust) {
                // console.log(config)
                //去重
                let yearlist = [{ Data_ID: 0, name: "全部" }, ...config.adjust.sort((a: any, b: any) => a.Data_ID - b.Data_ID).map((a: { Data_ID: any; }) => {
                    return {
                        Data_ID: a.Data_ID, name: `${a.Data_ID}`
                    }
                })]
                yearlist = yearlist.reduce((acc: any, curr: { Data_ID: any; }) => {
                    const index = acc.findIndex((item: { Data_ID: any; }) => item.Data_ID === curr.Data_ID)
                    if (index < 0) {
                        acc.push(curr)
                    }
                    return acc
                }, [])
                setVersionList(yearlist)
                // 是否选中的状态都要从本地数据库中获取
                // 全部传过去查询数据库

                let res = (await getAccountAdujustIsSelect({ dbName: zcbfid, data: config.adjust })).data

                iterator.items = res
                auditAjust.current = res.filter((a: { selected: any; }) => a.selected) // 获取选中的默认状态
                if (res.filter((a: { selected: any; }) => a.selected).length === 0) {
                    iterator.selected = false;
                }

            }
            if (iterator.id === leftTitleList.notes) {
                if (sjnd !== config.dataId) {
                    config.exportNoteIndex = config.exportNoteIndex.map((a: any) => {return { ...a, isselected: false, selected: false }})
                   
                } else {
                        // 本地时间
                    let table_list = await getDesignTabelEditDate({ dbName: zcbfid })
                    let note = await getDesignTabelEditDateCompare({ zcbfid: zcbfid, sjnd: sjnd, table_list: table_list.data.filter((a: any) => a.type === 'ds') }) as [{ editDate: string; }]
                    // console.log(note.data.map(a=>  a.name =a.title ));
                    config.exportNoteIndex = config.exportNoteIndex.map((a: any) => {
                        let res = note.filter((b: any) => b.id === a.id)

                        if (!res.length) {
                            return a;
                        } else {
                            //判断最新
                            if (a.editDate && res[0].editDate && (new Date(res[0].editDate)) < (new Date(a.editDate)) || (a.editDate && res[0].editDate === null)) {
                                return a;
                            } else {

                                return { ...a, isselected: true, selected: false }
                            }
                        }
                        //  // 选中的判断，包里的是最新的，或者本地没有，或者本地没有编辑时间
                        //  if ((res.length > 0 && a.editDate && res[0].editDate === null) || (res.length > 0 && a.editDate && new Date(res[0].editDate)  > new Date(a.editDate) ) || (a.editDate ==)) {
                    })

                }
            
                iterator.items = config.exportNoteIndex
                notes.current = config.exportNoteIndex.filter((a: any) => a.selected)
                // 财务初始化
                allnodedata.current.selectTrial = allnodedata.current.Trial
                if ( notes.current.length ===0 && allnodedata.current.Trial.length ==0) {
                    iterator.selected = false
                }
            }
            if (iterator.id === leftTitleList.dgfj) {
                // 获取底稿编辑时间，和最新的做对比，返回id，附件也是一样的
                let local = await getdgTreeList(zcbfid)
                config.exportdgIndex.map((a: any) => {
                    let res = local.filter((b: any) => b.id === a.id)
                    console.log(res, a.editDate, 'a')
                    if (res.length === 1) {
                        if ((new Date(a.editDate)) > (new Date(formatterChinaTime(res[0].editDate)))) {
                            TapActiveKeydgOrfj.current.selectdg.push(a)
                        }
                    } else {
                        TapActiveKeydgOrfj.current.selectdg.push(a)
                        // console.log(TapActiveKeydgOrfj.current.selectdg)
                    }
                })
                TapActiveKeydgOrfj.current.slectdgfj = allnodedata.current.dglinkfj.filter((a: any) => {
                    return TapActiveKeydgOrfj.current.selectdg.filter((b: any) => {
                        return a.dgid === b.id
                    }).length > 0
                })
                setDgdatalist(config.exportdgIndex)
                const res = await getApiData('dgfj.list', { dbname: zcbfid });
                let tem = res.data.map((a: any) => {
                    return { name: a.fjName + a.fjlx, id: a.fjid, editDate: a.LastEditDate, editUser: a.UserName }
                }
                )
                config.dgfj.map((a: any) => {
                    let res = tem.filter((b: any) => b.id === a.id)
                    // console.log(res,a)
                    if (res.length === 1) {
                        if ((new Date(a.editDate)) > (new Date(formatterChinaTime(res[0].editDate)))) {
                            TapActiveKeydgOrfj.current.selectFj.push(a)
                        }
                    } else {
                        TapActiveKeydgOrfj.current.selectFj.push(a)
                    }
                })
                if (TapActiveKeydgOrfj.current.selectdg.length === 0 && TapActiveKeydgOrfj.current.selectFj.length === 0) {
                    iterator.selected = false
                }
                // TapActiveKeydgOrfj.current.selectdg=res.map((a:any)=>a.id)
                // TapActiveKeydgOrfj.current.dg=res
            }
        }
        allnodedata.current.exportFirstIndex = config.exportFirstIndex
        setfirstTitle(config.exportFirstIndex) // 渲染一级栏目
        // console.log(allnodedata.current, "selected", firstTitle)
        await leftonItemsChange({ itemIndex: 0 }, config.exportFirstIndex);
        setLoadPanelVisible(false)
    }
    const setProgressInfoValueEvent = (data: any, count: any) => {
        // let count = firstTitle.filter((a:any)=>a.selected==true).length
        console.log(data, "data", count)
        setProgressInfoValue(((data / count) * 100).toFixed(2) as any)
    }
    // 异步事件间的关系，走全局变量
    const importresult = async (page: AudTabPage) => {
        if (isexport || firstTitle.filter((a: any) => a.selected).length === 0) {
            notify("没有可以导入的成果数据", 'error', 2000);
            return;
        }
        if (isAllowNoteRef.current) {
      
            setIsAllowNote(true);
            notify("附注选项中数据包的年度和当前项目年度不匹配，无法被导入，请重新选择", 'error', 2000);
            return;
        }
        // console.log(AudTabPage)
        // let selectList  = firstTitle.filter((a: any) => a.selected ).map((a:any)=>a.name )
        // // let msg=false || ''
        // // for (const key in selectList) {
        // //     if (selectList[key] === '底稿及附件') {
        // //         page.tabs.forEach((a: any) => {
        // //             if (a.title ==='底稿管理' || a.title ==='附件管理') { 
        // //                 msg= '底稿及附件'
        // //             }
        // //         })
        // //     }
        // //     if (selectList[key] === '调整分录') {
        // //         page.tabs.forEach((a: any) => {
        // //             if (a.title ==='审计调整' || a.title ==='账表调整') { 
        // //                 msg= '调整分录'
        // //             }
        // //         })
        // //     }
        // //     if (selectList[key] === '附注及试算') {
        // //         page.tabs.forEach((a: any) => {
        // //             if (a.title ==='附注与分析' || a.title ==='审定财务报表' || a.title ==='未定财务报表' || a.title ==='试算平衡表') { 
        // //                 msg= '附注及报表'
        // //             }
        // //         })
        // //     }
        // //     if (selectList[key] === '报告') {
        // //         page.tabs.forEach((a: any) => {
        // //             if (a.title ==='报告生成') { 
        // //                 msg= '报告生成'
        // //             }
        // //         })
        // //     }
        // //     if (selectList[key] === '组成部分设置') {
        // //         page.tabs.forEach((a: any) => {
        // //             if (a.title ==='批量设置') { 
        // //                 msg= '报告生成'
        // //                 page.closeTabByKey('/ReportSys/importResult')

        // //             }
        // //         })
        // //     }

        // //     if (msg) {
        // //         return notify(`关闭${msg}等页面`, 'error', 2000);
        // //     }   
        // // }

        setLoadPanelVisible(true)
        setProgressInfoVisible(true)
        // 异步事件间的顺序
        if ( firstTitle.filter((a: any) => a.id === leftTitleList.notes && a.selected).length && notes.current?.length) {
            ProgressCount.current.count = ProgressCount.current.count + 4
        }



        if (firstTitle.filter((a: any) => a.id === leftTitleList.notes && a.selected).length && allnodedata.current?.selectTrial?.length) {
            ProgressCount.current.count = ProgressCount.current.count + 4
        }
        let res = await importTemplate(zcbfid, sjxmbh,
            //获取栏目参数，默认全部，全部取消，无法导出
            selectedDisclosureTable.current.length === 0 ? firstTitle.filter((a: any) => a.selected) : selectedDisclosureTable.current,
            //firstTitle,
            // 底稿参数，默认全部，全部是布尔，全部取消，也无法导出是【】
            zcbf,
            TapActiveKeydgOrfj.current.selectdg as [{ dgnd: string; name: string; }],
            TapActiveKeydgOrfj.current.selectFj as [{ name: string; }],
            TapActiveKeydgOrfj.current.slectdgfj,
            auditAjust.current,
            // 附注
            notes.current,
            report.current ? report.current : allnodedata.current.report,
            sjnd,
            allnodedata.current.selectTrial,
            allnodedata.current.accountDateSet,
            allnodedata.current.zcbfid, allnodedata.current.sjxmbh,
        );

        setTimeout(() => {
            setProgressInfoValue(100)
            setLoadPanelVisible(false)
            setProgressInfoVisible(false)
            setIsMaskOpen(false)
            const audTabpage = AudTabPage.getInstance();
            audTabpage.closeTab('closeAll');
            console.log(audTabpage, "audTabpage")
            // 关闭所有页面
            history.push(audTabpage.activeTabKey);
            PubSub.clearAllSubscriptions();
            ProgressCount.current.index=0
            if (res) {
                if (typeof res ==='boolean') {
                    notify("导入成果成功,并关闭要导入部分的页面", 'success', 2000);    
                } else {
                    notify(`${res.toString()}请关闭这些文件再次导入`, 'success', 2000 * res.length); 
                }
                
            } else {
                notify("导入成果失败", 'error', 3000);
            }

        }, 800)


    }
    // 底稿附件点击记录
    const TwotreeListSelectionChanged = useCallback((e: any) => {
        const selectedData = e.component.getSelectedRowsData();

        if (TapActiveKeydgOrfj.current.key === "1") {
            TapActiveKeydgOrfj.current.selectdg = selectedData
            TapActiveKeydgOrfj.current.slectdgfj = allnodedata.current.dglinkfj.filter((a: any) => {
                return selectedData.filter((b: any) => {
                    return a.dgid === b.id
                }).length > 0
            })
        } else {
            // 保存选中记录
            TapActiveKeydgOrfj.current.selectFj = selectedData
        }
    }, []);
    const AuditAjustHead = () => {
        return (<div style={{ display: 'flex', alignItems: 'center', marginLeft: 10 }}> <div style={{ whiteSpace: 'nowrap' }}>套账：</div>
            <SelectBox
                width={200}
                items={versionList}
                defaultValue={auditAdjustFiterAccountDate}
                displayExpr='name'
                valueExpr='Data_ID'
                onValueChange={async (value) => {
                    // showDataRef.current.data_id = value;
                    setAuditAdjustFiterAccountDate(value)

                    let res = await getAccountAdujustInfo({ DataId: value, BillType: auditAdjustFiterBiilType })
                    setsecondTitle(res)
                }}
            />
            <div style={{ whiteSpace: 'nowrap', marginLeft: 5 }}>单据类型：</div>
            <SelectBox
                width={200}
                items={[{ id: -1, name: "全部" }, { id: 0, name: "账表调整" }, { id: 1, name: "审计调整" }]}
                defaultValue={auditAdjustFiterBiilType}
                displayExpr='name'
                valueExpr='id'
                onValueChange={async (value) => {

                    setAuditAdjustFiterBiilType(value)
                    let res = await getAccountAdujustInfo({ DataId: auditAdjustFiterAccountDate, BillType: value })
                    setsecondTitle(res)
                }}
            />
        </div>
        )
    }
    const LeftOne = () => {
        return <TreeView
            id="treeview1"
            width={'100%'}
            height={'calc(100vh - 250px)'}
            dataStructure="plain"
            onItemClick={leftonItemsChange}
            items={firstTitle}
            displayExpr="name"
            keyExpr="id"
            selectByClick={false}
            selectAllText="全选"
            showCheckBoxesMode={'normal'}
            virtualModeEnabled={true}
            selectionMode={'multiple'}
            selectNodesRecursive={false}
            onSelectionChanged={treeViewSelectionChanged}
        ></TreeView>
    }
    const LeftTwo = () => {
        return <TreeView
            id="treeview"
            width={'100%'}
            height={'calc(100vh - 250px)'}
            dataStructure="plain"
            parentIdExpr="pid"
            ref={treeViewRef}
            items={secondTitle}
            displayExpr={"name"}
            keyExpr="id"
            selectByClick={true}
            selectAllText="全选"
            showCheckBoxesMode={'selectAll'}
            virtualModeEnabled={true}
            selectionMode={'multiple'}
            selectNodesRecursive={false}
            onSelectionChanged={TwotreeViewSelectionChanged}
        ></TreeView>
    }
    const LeftDatatable = () => {
        return <DataGrid
            id="treelist"
            width={'100%'}
            height={'calc(100vh - 250px)'}
            dataStructure="plain"
            dataSource={dgdatalist}

            parentIdExpr="pid"
            keyExpr="id"
            rootValue='null'
            showRowLines={true}
            showBorders={true}
            columnAutoWidth={true}
            defaultSelectedRowKeys={TapActiveKeydgOrfj.current.selectdg.map((a: any) => a.id)}
            onSelectionChanged={TwotreeListSelectionChanged}
        >
            <Selection recursive={true} allowSelectAll={true} mode="multiple" />
            <Column dataField="dgnd" caption="年份" dataType="string" groupIndex={0} />
            <Column
                dataField="name"
                caption="项目"
            />
            <Column
                dataField="editDate"
                caption="修改日期"
            />
            <Column
                dataField="editUser"
                caption="编辑人"
            />
        </DataGrid>
    }
    const LeftDatatablefj = () => {
        //@ts-ignore
        return <DataGrid
            id="treelist"
            width={'100%'}
            height={'calc(100vh - 250px)'}
            dataStructure="plain"
            dataSource={dgdatalist}
            parentIdExpr="pid"
            keyExpr="id"
            rootValue={""}
            showRowLines={true}
            showBorders={true}
            columnAutoWidth={true}
            defaultSelectedRowKeys={TapActiveKeydgOrfj.current.selectFj.map((a: any) => a.id)}
            onSelectionChanged={TwotreeListSelectionChanged}
        >
            <Selection recursive={true} allowSelectAll={true} mode="multiple" />
            <Column
                dataField="name"
                caption="项目"
            />
            <Column
                dataField="editDate"
                caption="修改日期"
            />
            <Column
                dataField="editUser"
                caption="编辑人"
            />
        </DataGrid>
    }
    const ButtonEx = () => {
        return <div style={{ width: "100%", height: "40px", display: "flex" }}>
            <div style={{ display: 'flex', alignItems: "center", width: "100%" }} >
                <span style={{ width: "80px" }}> 文件包:</span>
                <div style={{ display: 'flex', alignItems: "center", width: "100%", border: "1px solid #ddd", borderRadius: "4px" }} >
                    <TextBox value={cataloguepath} style={{ border: "none" }} />
                    <span style={{ width: "25px", marginLeft: "5px" }}>
                        <CpasIcon type='icon-daochudigao' fontSize={16}
                            onClick={async () => {
                                //，获取解压文件，并进行渲染
                                await exportResult()
                            }}
                        />
                    </span>
                </div>
            </div>
            {/* <div style={{ width: "13%", display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Button text='导入'      type="default"
                stylingMode="contained" onClick={async () => { await importresult();}}></Button>
        </div> */}
        </div>
    }
    // 页面部分路由显示
    const RightLayt = () => {
        switch (currentid) {
            case 2:
                return <div id="employee" style={{ marginLeft: '10px', marginRight: '8px' }}>
                    <AntTabs
                        activeKey={TapActiveKeydgOrfj.current.key}
                        onChange={(val: string) => { dgChangeTabsKey(val) }}
                        destroyInactiveTabPane={false}
                        type="card"
                    >
                        <AntTabs.TabPane key="1" type="1" tab="底稿"><LeftDatatable /></AntTabs.TabPane> <AntTabs.TabPane type="1" key="2" tab="附件"><LeftDatatablefj /></AntTabs.TabPane>
                    </AntTabs></div>
            case leftTitleList.auditAdjust:
                return <div id="employee" style={{ marginLeft: '10px', marginRight: '8px' }}>  {useMemo(() => { return <AuditAjustHead /> }, [])}     <LeftTwo /></div>
            case leftTitleList.notes:
                return <div id="employee" style={{ marginLeft: '10px', marginRight: '8px' }}>
                    <AntTabs
                        activeKey={TapActiveKey}
                        onChange={(val: string) => { notechangeTabsKey(val) }}
                        destroyInactiveTabPane={false}
                        type="card"
                    >
                        <AntTabs.TabPane key="1" type="1" tab="附注"><LeftTwo /></AntTabs.TabPane> <AntTabs.TabPane type="1" key="2" tab="财务"><LeftTwo /></AntTabs.TabPane>
                    </AntTabs></div>
            default:
                return <div id="employee" style={{ marginLeft: '10px', marginRight: '8px' }}> <LeftTwo /></div>
        }
    }
    return <Modal title="项目成果导入" onOk={() => { importresult(audTabpage) }}
        onCancel={() => {

            audTabpage.closeTab('closeCur');
            history.push(audTabpage.activeTabKey);
            PubSub.clearAllSubscriptions();
            setIsMaskOpen(false)
        }} open={isMaskOpen} keyboard={true}    okButtonProps={{ disabled: isAllowNote }} maskClosable={false} centered={true} closable={true} width={'80%'} destroyOnClose={true} forceRender={true} okText='导入'>    <ButtonEx />  <LayoutB
            rowSize={['10%', '150px', '90%']}
            leftSlot={
                <div  ><LeftOne /></div>
            }
            rightSlot={
                <RightLayt />
            }
        >
        </LayoutB>
        {/* <Popup
                    contentRender={() => `${res.toString()}请关闭这些文件再次导入 ,并关闭要导入部分的页面`}
                    hideOnOutsideClick={true}
                    // onHiding={togglePopup}
                    resizeEnabled={true}
        /> */}
        <LoadPanel
            shadingColor="rgba(0,0,0,0.4)"
            position="center"
            // onHiding={hideLoadPanel}
            visible={loadPanelVisible}
            showIndicator={true}
            shading={true}
            showPane={true}
            message={msg}
        />
        {ProgressInfoVisible ? <Tooltip popupVisible={false} title="">
            <Progress percent={ProgressInfoValue} />
        </Tooltip> : <></>}
    </Modal>
}

export default ReportExport;
